package cn.com.callback;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import com.wisdge.web.springframework.SpringContextUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.codec.digest.HmacUtils;

public class TimerSendMsg implements CallBackInvoke{
	private static final Log log=LogFactory.getLog(TimerSendMsg.class);
	private String key = "";      
	private String secret = "";
    private static int COUNT  = 1;                                     //发送失败之后最多重发次数
    private static long flag = 0;  
	private String url = "";      
           
	//public String doCallBack(EliteBean eliteBean, HttpServletRequest request,HttpServletResponse response){
	public void doCallBack(EliteBean eliteBean,String callBack,Map map,String paramString){
		JdbcTemplate jt = new JdbcTemplate((DataSource)SpringContextUtil.getBean("dataSource"));   //获取数据源
		try {
			String querySqlurl = "select WEBSERVICE_DESC url from c_webservice_type where WEBSERVICE_ID = '2001'";
			EliteBean bean = new EliteBean();
			List<Map<String,Object>> listurl = bean.chaxun_sql(querySqlurl, "dataSource");
			log.debug("listurl:"+listurl.toString());
			url = listurl.get(0).get("url").toString();
			log.debug("url:"+ url); 
			String querySqlkey = "";

			String querySql = "select DOCUMENTTO mobileNo, DOCUMENTPATH content,DOCUMENTOUT_GUID guid,case when yc.skey is not null then yc.skey else 'ccs_test'end key,case when yc.secret is not null then yc.secret else '123abcJKL' end secret  from documentout d left join yc_smssendlevel yc on d.sms_lvl = yc.slevel where DOCTYPE = 3 and ((Status = 0) or (Status != 1 and TrialCount < TrialCountLimit)) and expectedstartdate <= sysdate and expectedstartdate >= sysdate - 5 / (24 * 60)";
			log.debug("querySql:" + querySql);
			List<Map<String, Object>> list = jt.queryForList(querySql);
			for(Map<String, Object> mapTemp: list){
				String mobileNo = (String)mapTemp.get("mobileNo");
				String content = (String)mapTemp.get("content");
				String guid = (String)mapTemp.get("guid");
				key = (String)mapTemp.get("key");
				secret = (String)mapTemp.get("secret");
				log.debug("mobileNo:" + mobileNo + " content:" + content + "guid:" + guid + "key:" + key + "secret:" + secret);
				String result = generateParam(0, mobileNo, content);
				log.debug("result:" + result);
				if(result != null && result.contains("s8m5pg==")){
					String querySql1 = "update documentout set status = 1 where DOCUMENTOUT_GUID = '" + guid + "'";
					jt.update(querySql1)
					log.debug("发送成功");
				} else {
					String querySql1 = "update documentout set status = 5,TRIALCOUNT = TRIALCOUNT+1 where DOCUMENTOUT_GUID = '" + guid + "'";
					jt.update(querySql1)
					log.debug("发送失败");
				}
			}
		} catch (Exception e) {
			log.error("TimerSendMsg.e", e);
		}
	}
	
	 public String send(String timestamp, String signature, String data,String key) throws Exception {
        String result = "";
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setReadTimeout(2000);
        // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("API-Key", key);
        conn.setRequestProperty("timestamp", timestamp);
        conn.setRequestProperty("Signature", signature);
        
        conn.connect();
        // 获取URLConnection对象对应的输出流
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.write(data);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }
    //使用finally块来关闭输出流、输入流
        if (out != null) {
            out.close();
        }
        if (bufferedReader != null) {
        	bufferedReader.close();
        }
        return result;
    }

    public String generateParam(int tryTime, String phone, String content) throws Exception {
        String encodeContent = "";
        String data = "";
        sun.misc.BASE64Encoder base64 = new sun.misc.BASE64Encoder();
        encodeContent = base64.encode(content.getBytes("GBK"));
    	encodeContent = URLEncoder.encode(encodeContent, "GBK");

       /* String sss[] = phone.split(",");
        for (int i = 0; i < sss.length; i++) {
            if (sss[i] != null && !"".equals(sss[i]))
                data += "mobiles=" + sss[i] + "&";
        }

        data += "sms=" + encode_content;*/
        data="mobiles="+phone+"&sms="+encodeContent;
        log.debug(data);
        //时间戳
        long t = System.currentTimeMillis() - flag;

        String apikey = key; //即 API-Key
        String apisecret = secret;
        String data2sign = data + apikey + t;
        //签名
        String signature = HmacUtils.hmacSha1Hex(apisecret, data2sign); // Signature
        String result = send(t + "", signature, data, apikey);

        if (result == null || !result.contains("s8m5pg==")) {
            if (tryTime < COUNT) {
            	tryTime ++;
                flag = COUNT * 30 * 1000;
                generateParam(tryTime, phone, content);
            }else {
            	log.error("重试发送次数超过5次，发送失败");
            }
        }
        return result;
    }
}